package com.dubbo.lian.common.util;

import com.alibaba.fastjson.JSONObject;
import com.dubbo.lian.common.exception.WeatherException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/11/22 0022.
 */
public class WeatherUtil {
    protected static Logger logger = LoggerFactory.getLogger(WeatherUtil.class);

    public static JSONObject getWeatherAll(String cityname) throws WeatherException {
        Map map = new HashMap();
        map.put("key", "8f50b53a5ff8c3bd5239c1001b6b74a7");
        map.put("cityname", cityname);
        map.put("dtype", "json");
        JSONObject json = HttpUtil.postAsJson(map,"http://op.juhe.cn/onebox/weather/query");
        logger.debug(json.toJSONString());
        if(0 != json.getIntValue("error_code")){
            throw new WeatherException(json.toJSONString());
        }

        return json;
    }

    public static String getWeatherInfo(String cityname) throws WeatherException {
        JSONObject weatherJson = getWeatherAll(cityname);
        String weatherInfo;
            weatherInfo = weatherJson.getJSONObject("result")
                    .getJSONObject("data")
                    .getJSONObject("realtime")
                    .getJSONObject("weather")
                    .getString("info");
        return weatherInfo;
    }


    public static HashMap getOutDoorWeather(String cityname) throws WeatherException {
        JSONObject weatherJsonR = getWeatherAll(cityname);
        HashMap hm = new HashMap();
        JSONObject dataJson = weatherJsonR.getJSONObject("result").getJSONObject("data");
        JSONObject weatherJson = dataJson.getJSONObject("realtime").getJSONObject("weather");
        logger.debug(weatherJson.toJSONString());

        int pm25 = dataJson.getJSONObject("pm25").getJSONObject("pm25").getInteger("pm25");

        int temperature = weatherJson.getInteger("temperature");

        int humidity = weatherJson.getInteger("humidity");
        logger.debug("pm25"+pm25+";temperature"+temperature+";humidity"+humidity);
        hm.put("pm25",pm25);
        hm.put("temperature",temperature);
        hm.put("humidity",humidity);
        return hm;
    }



}
